package com.itxiaosu.pojo.base;

import com.itxiaosu.strategy.DiscountStrategy;

import java.util.HashMap;
import java.util.Map;

// 购物车类，负责计算总价
public class ShoppingCart {
    private final DiscountStrategy discountStrategy;
    private final Map<Fruit, Integer> fruitQuantityMap;

    public ShoppingCart(DiscountStrategy discountStrategy) {
        this.fruitQuantityMap = new HashMap<>();
        this.discountStrategy = discountStrategy;
    }

    /**
     * 向购物车中添加指定数量的水果
     *
     * @param fruit    要添加的水果
     * @param quantity 水果的数量
     */
    public void addFruit(Fruit fruit, int quantity) {
        fruitQuantityMap.put(fruit, fruitQuantityMap.getOrDefault(fruit, 0) + quantity);
    }


    /**
     * 计算购物车中所有水果的总价
     *
     * @return 购物车中所有水果的总价
     */
    public double calculateTotal() {
        double total = 0;
        for (Map.Entry<Fruit, Integer> entry : fruitQuantityMap.entrySet()) {
            Fruit fruit = entry.getKey();
            int quantity = entry.getValue();
            total += fruit.calculateTotal(quantity);
        }
        return discountStrategy.discountType(total);
    }

    public DiscountStrategy getDiscountStrategy() {
        return discountStrategy;
    }
}
